package archer.framework.web.listener;

import archer.framework.utils.ProfileUtils;
import archer.framework.utils.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;

/**
 * 系统环境属性初始化监听
 *
 * @author christ
 * @date 2016/4/18
 */
public class SystemProfileInitListener extends BeforeSpringInitListener {

    private static final Logger logger = LoggerFactory.getLogger(SystemProfileInitListener.class);

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

        super.contextInitialized(servletContextEvent);

        if (ValidateUtils.isNotEmpty(System.getProperty(ProfileUtils.ACTIVE_PROFILE))) {
            logCurrentProfile();
            return;
        }

        //取web.xml中值
        String profileContextParam = servletContextEvent.getServletContext().getInitParameter(ProfileUtils.ACTIVE_PROFILE);
        //本地开发时取出的是占位符
        if (("${" + ProfileUtils.CONFIG_PROFILE + "}").equals(profileContextParam)) {
            System.setProperty(ProfileUtils.ACTIVE_PROFILE, System.getProperty(ProfileUtils.CONFIG_PROFILE));
            logCurrentProfile();
            return;
        }

        //线上使用web.xml中值
        System.setProperty(ProfileUtils.ACTIVE_PROFILE, profileContextParam);

        logCurrentProfile();

    }

    protected void logCurrentProfile() {

        logger.error("PROFILE>>---------------------" + ProfileUtils.getCurrentProfile() + "---------------------");
    }
}
